<template>
    <div class="article-list">
        <!-- 文章列表——头部 -->
        <div class="list-header">
            <h3>文章列表</h3>
        </div>
        <div class="list-filter">
            <div class="filter">
              <span>文章分类</span>
              <el-select v-model="typeValue" placeholder="请选择分类" >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <span>发布状态</span>
              <el-select v-model="stateValue" placeholder="请选择状态" >
                <el-option
                  v-for="item in stateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-button type="primary">筛选</el-button>
              <el-button>重置</el-button>
            </div>
            <el-button type="primary" @click="showDrawer= true">新增文章</el-button>
        </div>
        <!-- 文章列表——内容 -->
        <div class="list-main">
            <el-table
            border
            :data="articleData"
            style="width: 100%">
            <el-table-column
                prop="title"
                label="标题"
                width="380">
            </el-table-column>
            <el-table-column
                prop="cate_name"
                label="分类"
                width="120">
            </el-table-column>
            <el-table-column
                prop="pub_date"
                label="发表时间">
            </el-table-column>
            <el-table-column
                prop="state"
                label="状态"
                width="200"
                >
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="160">
                <template slot-scope="scope">
                    <el-button @click="editArt(scope.row.id)"  size="small">修改</el-button>
                    <el-button @click="delArticle(scope.row.id)" size="small" class="delBtn">删除</el-button>
                </template>
            </el-table-column>
            </el-table>
            <div class="list-page">
                <el-pagination
                :current-page="pageInfo.pagenum"
                :page-sizes="[5,10]"
                :page-size= "pageInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageInfo.pageTotal">
                </el-pagination>
            </div>
        </div>
        <!-- 文章列表——内容——结束 -->

        <!-- 抽屉组件 -->
        <el-drawer
            title="发表文章"
            :visible.sync="showDrawer"
            class="list-drawer"
            size="80%"
            :before-close="befClose"

            >
            <el-form label-position="right" ref="myForm" id="myForm" :model="artData" :rules="artRules">
                <el-form-item label="文章标题" label-width="100px" style="font-size: 14px;" prop="title">
                    <el-input autocomplete="off" size="middle" placeholder="请输入文章标题" v-model="artData.title" name="title"></el-input>
                </el-form-item>
                <el-form-item label="文章分类" label-width="100px" style="font-size: 14px;" prop="cate_id">
                    <el-input autocomplete="off" size="middle" placeholder="请输入文章分类" v-model="artData.cate_id" name="cate_id"></el-input>
                </el-form-item>
                <el-form-item label="文章内容" label-width="100px" style="font-size: 14px;" class="ql-item" prop="content">
                    <quill-Editor :height="300" v-model="artData.content" name="content"></quill-Editor>
                </el-form-item>
                <el-form-item label="文章封面" label-width="100px" style="font-size: 14px; height: 300px;">
                    <!-- 头像上传 -->
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                        <span>更换头像</span>
                        </div>
                        <div>
                        <!-- 图片，用来展示用户选择的头像 -->
                        <img :src="artData.cover_img" alt="" style="width:350px;"  v-if="artData.cover_img"/>
                        <img src="../../assets/images/cover.jpg" alt=""  v-else />

                        <!-- 按钮区域 -->
                        <div class="btn-box">
                            <input type="file" style="display:none;" ref="imgFiles" @change="onIptChange" name="cover_img" >
                            <el-button type="success" icon="el-icon-upload"  @click="addOk">发布</el-button>
                            <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
                        </div>
                        </div>
                    </el-card>
                </el-form-item>
            </el-form>
            <!-- 关闭提示框 -->
            <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%"
            >
            <span>此操作将导致文章信息丢失，是否继续？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="closeOk">确 定</el-button>
            </span>
            </el-dialog>
        </el-drawer>

    </div>
</template>

<script>
import { getArticleList, addArticle, getArticleDetail, editArticle, delArticle } from '@/api/article'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css' // import styles
import 'quill/dist/quill.snow.css' // for snow theme
import 'quill/dist/quill.bubble.css' // for bubble theme

export default {
  components: {
    quillEditor
  },
  // data
  data () {
    return {
      // 分类选择器
      typeOptions: [{ value: '新闻', label: '新闻' }, { value: 'hello world', label: 'hello world' }],
      typeValue: '',
      // 发布选择器
      stateOptions: [{ value: '已发布', label: '已发布' }, { value: '草稿', label: '草稿' }],
      stateValue: '',

      articleData: [],
      // 页码相关
      pageInfo: {
        pagenum: 1,
        pagesize: 10
      },
      pageTotal: 1,
      // 弹框数据
      showDrawer: false,
      // 发表文章——文章相关
      artData: {
        title: '',
        cate_id: null,
        content: '',
        state: '已发布',
        cover_img: '',
        // 额外添加
        id: null
      },
      artRules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        cate_id: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章标题', trigger: 'blur' }]

      },

      // 关闭对话框
      dialogVisible: false
    }
  },
  // created
  async created () {
    // 初始化文章
    this.getList()
  },
  // methods
  methods: {
    // 修改按钮——获取文章详情
    async editArt (id) {
      this.showDrawer = true
      //   console.log(id)
      const res = await getArticleDetail(id)
      //   console.log(res)
      this.artData = { ...res.data }
      console.log(this.artData)
    },
    // 删除按钮——删除文章
    async delArticle (id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(async _ => {
        await delArticle(id)
        this.$message.success('删除文章成功')
        this.getList()
      })
        .catch(() => {
          console.log('取消啦')
        })
    },
    // 关闭前回调
    befClose () {
      this.dialogVisible = true
    //   this.$confirm('确认关闭吗？').then(_ => {
    //     done()
    //   })
    //     .catch(_ => {})
    },
    closeOk () {
      this.dialogVisible = false
      this.showDrawer = false
      this.$refs.myForm.resetFields()
      this.artData.cover_img = ''
    },
    // 渲染文章列表
    async getList () {
      const res = await getArticleList(this.pageInfo)
      this.articleData = res.data
      this.pageTotal = res.total
    },
    // 文章弹框——发布文章
    addOk () {
      // 如果有id则为编辑
      if (this.artData.id) {
        this.$refs.myForm.validate(async (isOk) => {
          if (isOk) {
            if (this.artData.cover_img) {
              const formData = new FormData(document.getElementById('myForm'))
              formData.append('content', this.artData.content)
              formData.append('state', this.artData.state)
              formData.append('id', this.artData.id) // 新增Id
              await editArticle(formData)
              // 关闭弹层
              this.$message.success('更新文章成功')
              // 重置表单和数据
              this.$refs.myForm.resetFields()
              this.artData = {
                title: '',
                cate_id: null,
                content: '',
                state: '已发布',
                cover_img: '',
                // 额外添加
                id: null
              }
              this.showDrawer = false
              // 重新渲染
              this.getList()
            } else {
              this.$message.warning('请选择封面图片')
            }
          }
        })
      } else {
        this.$refs.myForm.validate((isOk) => {
          if (isOk) {
            if (this.artData.cover_img) {
              this.upLoad()
            } else {
              this.$message.warning('请选择封面图片')
            }
          }
        })
      }
    },
    // 点击button触发input点击事件
    chooseImg () {
      this.$refs.imgFiles.click()
    },

    onIptChange (e) {
      // input内容改变事件
      // e拿到事件对象
      // e.target.files是个伪数组/可以通过长度判断用户是否选择了图片

      if (e.target.files.length === 0) {
        // 点击了取消了,就恢复默认图片
        this.artData.cover_img = ''
      } else {
        // FileReader 浏览器提供的方法
        const reader = new FileReader()
        // reader里面有个方法readAsDataURL 可以将图片转base64进制
        reader.readAsDataURL(e.target.files[0])
        // onload可以监听转换完成后
        reader.onload = () => {
        // 给声明变量赋值
          console.log(reader)
          this.artData.cover_img = reader.result
        }
      }
    },
    // 封装上传函数
    async  upLoad () {
      const formData = new FormData(document.getElementById('myForm'))
      //  步骤：1.将内容放进formData   2.调用api   3.成功提示   4.重新渲染  5.关闭弹框重置表单
      //   formData.append('cover_img', this.artData.cover_img)
      //  图片上传只能用name
      formData.append('content', this.artData.content)
      formData.append('state', this.artData.state)
      const res = await addArticle(formData)
      this.$message.success('新增文章成功')
      console.log(res)
      this.getList()
      // 关闭弹框 重置表单
      this.$refs.myForm.resetFields()
      this.artData.cover_img = ''
      this.showDrawer = false
    }
  }
}
</script>

<style lang="less" scoped>
    .article-list{
        padding: 30px;
        width: 100%;
        height: 100%;
        // 头部
        .list-header{
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0px 30px;

            height: 70px;
            background: #FFFFFF;
            border-radius: 4px 4px 0px 0px;

            h3{
                font-size: 16px;
                color: #131523;
                font-weight: 700;
            }
        }
        // 筛选器
        .list-filter{
            display: flex;
            justify-content: space-between;
            padding-left: 30px ;
            padding-right: 30px;
            height: 70px;
            background: #FFFFFF;
            .el-button{
              height: 32px;
            }
            span{
              margin-right: 10px;
              margin-left: 10px;
              font-size: 14px;
              color: rgba(0,0,0,0.40);
              text-align: left;
              font-weight: 400;
            }
            .el-select{
              margin-right: 10px;
            }
        }
        .list-page{
            margin-top: 30px;
        }
        // 内容
        .list-main{
            padding: 0px 30px;

            background-color: #FFFFFF;
            .el-table{
                color: #131523;
                .el-button{
                    background: #4F81FF;
                    border-radius: 4px;
                    color: white;
                }
                .delBtn{
                    background: #F46C6C;
                    border-radius: 4px;
                    color: white;
                }
            }

        }
        // 抽屉组件
        .list-drawer{
            width: 100%;
            height: 100%;

            .el-input-item__label{
                font-size: 16px;
            }
            .quill-editor{
                .ql-editor{
                height: 100px;
            }
            }

            // 头像上传样式
            .avatar-uploader .el-upload {
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                }
                .avatar-uploader .el-upload:hover {
                    border-color: #409EFF;
                }
                .avatar-uploader-icon {
                    font-size: 28px;
                    color: #8c939d;
                    width: 178px;
                    height: 178px;
                    line-height: 178px;
                    text-align: center;
                }
                .avatar {
                    width: 178px;
                    height: 178px;
                    display: block;
                }
            }
            // 按钮栏样式
            .draw-footer{
                padding-left: 30px;
            }

    }
</style>
